#include "server.h"
#include <QTcpServer>
#include <QtNetwork>
#include <QDebug>
#include <QByteArray>
#include <QDataStream>

Server::Server(QObject *parent): QObject(parent)
{
    tcpServer = new QTcpServer(this);
    if(!tcpServer->listen(QHostAddress::LocalHost, 6666)){
        qDebug()<<tcpServer->errorString();
        qApp->quit();
    }
    QObject::connect(tcpServer, &QTcpServer::newConnection, this, &Server::sendMessage);
}

void Server::sendMessage()
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);

    out.setVersion(QDataStream::Qt_5_0);
    out<<(quint16)0;
    out<<("hello tcp");
    out.device()->seek(0);
    out<<(quint16)(block.size() - sizeof(quint16));

    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    QObject::connect(clientConnection,&QTcpSocket::disconnected,clientConnection,&QTcpSocket::deleteLater);

    clientConnection->write(block);
    clientConnection->disconnectFromHost();
    qDebug()<<"server send msg."<<block.size();
}
